package com.wthink.hzgj.station

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import com.google.android.flexbox.FlexboxLayoutManager
import com.wthink.hzgj.Constants
import com.wthink.hzgj.R
import com.wthink.hzgj.databinding.FragmentStationBinding
import com.wthink.hzgj.station.adapter.StationAdapter
import com.wthink.hzgj.station.data.Station
import com.wthink.hzgj.station.viewmodel.StationViewModel
import com.wthink.hzgj.util.ClickUtil
import com.wthink.hzgj.util.adapter.OnItemClickListener
import com.wthink.hzgj.util.closeDefaultAnimator

class StationFragment : Fragment() {

    val viewModel by viewModels<StationViewModel>()
    private lateinit var binding: FragmentStationBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(
            inflater,
            R.layout.fragment_station,
            container,
            false
        )
        binding.viewModel = viewModel
        binding.lifecycleOwner = this
        return binding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        binding.back.setOnClickListener {
            it.findNavController().popBackStack()
        }

        binding.stationListView.layoutManager = FlexboxLayoutManager(context)
        binding.stationListView.adapter = StationAdapter().apply {
            mItemClickListener = object : OnItemClickListener {
                override fun onItemClick(obj: Any, position: Int) {
                    viewModel.select(obj as Station)
                }
            }
        }

        closeDefaultAnimator(binding.stationListView)

        binding.up.setOnClickListener {
            viewModel.loadUpdir(true)
        }

        binding.down.setOnClickListener {
            viewModel.loadUpdir(false)
        }

        binding.arrive.setOnClickListener {
            if (ClickUtil.isNotFastClick()) {
                Log.d("点击了","点击了")
                viewModel.arrive()
            }
        }

        binding.leave.setOnClickListener {
            if (ClickUtil.isNotFastClick()) {
                viewModel.leave()
            }
        }

        viewModel.start(arguments!!.getString("lineId")!!, arguments!!.getString("lineName")!!)
    }

    fun setkeyDown(scanCode: Int) {
        Log.d("stationkeydown","keycode->"+scanCode)
        when (scanCode) {
            Constants.KEYCODE_PLAY->{
                viewModel.arrive()
            }
            Constants.KEYCODE_REPLAY->{
                viewModel.arrive()
            }
        }
    }
}
